package org.karelun.gef.parts;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPart;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.RGB;
import org.karelun.gef.figure.StateStartFigure;
import org.karelun.gef.model.Node;
import org.karelun.gef.model.NodeConstants;
import org.karelun.gef.model.StateStartModel;
import org.karelun.gef.utils.FontDataUtils;

public class StateStarPart extends NodePart {

	protected IFigure createFigure() {
		return new StateStartFigure();
	}
	
	@Override
	protected void refreshVisuals() {
		StateStartModel start = (StateStartModel) getModel();
		StateStartFigure figure = (StateStartFigure) getFigure();
		figure.setText(start.getText());
		
		RGB foreColor = start.getForeColor();
		if(foreColor!=null)
			figure.setForeColor(foreColor);
		RGB bgColor = start.getBgColor();
		if(bgColor!=null)
			figure.setBGColor(bgColor);
		FontData fontData = start.getFontData();
		if(fontData!=null)
			figure.setFontData(fontData);
		
		refreshFigureConstraint(figure, start);
		
		super.refreshVisuals();
	}
	
	private void refreshFigureConstraint(IFigure figure,Node node){
		Dimension size = node.getSize();
		FontData data = node.getFontData();
		if(data!=null)
			size = FontDataUtils.getFontSize(node.getText(), data);
		
		Rectangle rectangle = new Rectangle(node.getLocation(), size);
		EditPart parent = getParent();
		((DiagramPart) parent).setLayoutConstraint(this,
				getFigure(), rectangle);
	}
	
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(NodeConstants.PROP_TARGET))
			refreshTargetConnections();
		else if (evt.getPropertyName().equals(NodeConstants.PROP_SOURCE))
			refreshSourceConnections();
		else if(NodeConstants.PROP_LOCATION.equals(evt.getPropertyName())
				||NodeConstants.PROP_SIZE.equals(evt.getPropertyName()))
			refreshVisuals();
		
		if (NodeConstants.PROP_TEXT.equals(evt.getPropertyName())
				||NodeConstants.PROP_FORE_COLOR.equals(evt.getPropertyName())
				||NodeConstants.PROP_BG_CLOR.equals(evt.getPropertyName())
				||NodeConstants.PROP_FONT.equals(evt.getPropertyName())) {
			refreshVisuals();
		}
		super.propertyChange(evt);
	}
	
	public void activate() {
		super.activate();
		((Node) getModel()).addPropertyChangeListener(this);
	}

	public void deactivate() {
		((Node) getModel()).removePropertyChangeListener(this);
		super.deactivate();
	}
}